<?php

namespace app\controller;

use app\APIResponse;
use app\BaseController;
use think\facade\Request;
use think\facade\Validate;
use think\facade\Db;
use Firebase\JWT\JWT;

class System extends BaseController {
    /**
     * 测试用户数据
     * @var array
     */
    private $testUser = [
        'id' => 1,
        'username' => 'admin',
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // 密码：password
        'nickname' => '管理员',
        'avatar' => 'https://example.com/avatar.jpg'
    ];

    /**
     * 用户登录
     * @param Request $request
     * @return \think\Response
     */
    public function login(Request $request) {

        // return APIResponse::success(env());
        // return APIResponse::error(config("app"));

        // 获取参数
        $username = Request::param('username');
        $password = Request::param('password');

        // 参数验证
        $validate = Validate::rule([
            'username' => 'require|length:3,20',
            'password' => 'require|length:6,20'
        ]);
        if (!$validate->check(['username' => $username, 'password' => $password])) {
            return APIResponse::error($validate->getError());
        }

        // 验证用户名
        if ($username !== $this->testUser['username']) {
            return APIResponse::error('用户不存在');
        }

        // 验证密码
        if (!password_verify($password, $this->testUser['password'])) {
            return APIResponse::error('密码错误');
        }

        // 生成token
        $token = $this->createToken($this->testUser['id']);

        // 返回用户信息和token
        return APIResponse::success([
            'token' => $token,
            'user'  => [
                'id'       => $this->testUser['id'],
                'username' => $this->testUser['username'],
                'nickname' => $this->testUser['nickname'],
                'avatar'   => $this->testUser['avatar'],
            ]
        ], '登录成功');
    }

    /**
     * 生成JWT token
     * @param int $userId 用户ID
     * @return string
     */
    private function createToken($userId) {
        $key = config('jwt.secret'); // 从配置文件获取密钥
        $time = time();
        $token = [
            'iss'  => 'momo', // 签发者
            'aud'  => 'momo', // 接收者
            'iat'  => $time, // 签发时间
            'nbf'  => $time, // 生效时间
            'exp'  => $time + 7200, // 过期时间：2小时
            'data' => [
                'uid' => $userId
            ]
        ];
        return JWT::encode($token, $key, 'HS256');
    }
}